ayuta.namespace("ayuta.gears");

ayuta.gears.Transaction = new ayuta.Class({
    initialize: function(gearsDatabase) {
        this._conn = gearsDatabase;
    },
    begin: function() {
        if (this._conn.transactionDepth <= 0) 
            this._conn.execute("BEGIN");
        this._conn.transactionDepth++;
    },
    commit: function() {
        this._conn.transactionDepth = Math.max(0, --this._conn.transactionDepth);
        if (this._conn.transactionDepth <= 0) 
            this._conn.execute("COMMIT");
    },
    rollback: function() {
        if (this._conn.transactionDepth > 0) {
            this._conn.transactionDepth = 0;
            this._conn.execute("ROLLBACK");
        }
    },
    exec: function(fn, bind) {
        try {
            this.begin();
            var ret = fn.apply(bind || this, []);
            this.commit();
            return ret;
        } catch (e) {
            this.rollback();
            throw e;
        }
    }
});
